package com.ptone.messageCenter.config.interceptor;

import com.alibaba.fastjson.JSON;
import com.ptone.messageCenter.common.response.ErrCode;
import com.ptone.messageCenter.common.response.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * 访问控制
 */
@Component
public class AccessInterceptor implements HandlerInterceptor {

    /**
     * response状态自定义返回
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        if (response.getStatus() == 500)
            handleNotAuthorized(response, ErrCode.SYSTEM_ERROR);
        else if (response.getStatus() == 404)
            handleNotAuthorized(response, ErrCode.INTERFACE_DOES_NOT_EXIST);
    }


    /**
     * 自定义返回的错误代码和信息
     *
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void handleNotAuthorized(HttpServletResponse response, ErrCode code) throws IOException {
        if (code == ErrCode.OK) return;
        //让浏览器用utf8来解析返回的数据
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        String data = JSON.toJSONString(Result.fail(code));
        OutputStream ps = response.getOutputStream();
        //使得放入流的数据是utf8格式
        ps.write(data.getBytes(StandardCharsets.UTF_8));
    }

}
